import click
import pymysql

from utils import config_read


@click.command()
@click.option('--config', default='config.json', help='配置文件')
def init_db(config):
    sql_info_list = config_read(config)
    for sql_info in sql_info_list:
        # 创建数据库连接
        connection = pymysql.connect(host=sql_info.host,
                                     user=sql_info.user,
                                     password=sql_info.passwd,
                                     port=sql_info.port,
                                     database='mysql')  # 使用 mysql 数据库连接
        try:
            # 创建游标对象
            cursor = connection.cursor()

            # 读取SQL脚本文件
            with open(f'./db/{sql_info.db}.sql', 'r', encoding='utf-8') as file:
                sql_script = file.read()

            # 分割 SQL 脚本为单独的 SQL 语句
            sql_statements = sql_script.split(';')

            # 执行每个 SQL 语句
            for statement in sql_statements:
                statement = statement.strip()
                if statement:  # 过滤掉空语句
                    cursor.execute(statement)

            # 提交更改
            connection.commit()

        except Exception as e:
            print('执行异常:', e)
            connection.rollback()  # 如果发生异常，回滚事务
        finally:
            # 关闭游标和连接
            cursor.close()
            connection.close()
            print(f'执行sql文件成功')


if __name__ == '__main__':
    init_db()
